package com.tsinghuabigdata.edu.ddmath.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.MainActivity;
import com.tsinghuabigdata.edu.ddmath.activity.SelectQuestionsActivity;
import com.tsinghuabigdata.edu.ddmath.adapter.DoudouWorkAdatper;
import com.tsinghuabigdata.edu.ddmath.adapter.HomePageAdapter;
import com.tsinghuabigdata.edu.ddmath.adapter.OnlineTutoringAdapter;
import com.tsinghuabigdata.edu.ddmath.adapter.ToSubmitAdatper;
import com.tsinghuabigdata.edu.ddmath.adapter.UploadAdatper;
import com.tsinghuabigdata.edu.ddmath.bean.ClassInfo;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.MyCourse;
import com.tsinghuabigdata.edu.ddmath.bean.OnlineTutoring;
import com.tsinghuabigdata.edu.ddmath.bean.Records;
import com.tsinghuabigdata.edu.ddmath.bean.StudentsBean;
import com.tsinghuabigdata.edu.ddmath.bean.SubmitQuestion;
import com.tsinghuabigdata.edu.ddmath.bean.SumbitedItem;
import com.tsinghuabigdata.edu.ddmath.bean.TeacherBean;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.AppAsyncTask;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.dialog.SelectTimeDialog;
import com.tsinghuabigdata.edu.ddmath.module.login.view.LoginFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.view.RegisterFragment;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.SetHeadImage;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.LocalWorkManager;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.WaitUploadActivity;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.XBookCameraActivity;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.bean.WaitWorkBean;
import com.tsinghuabigdata.edu.ddmath.requestHandler.MyLearnService;
import com.tsinghuabigdata.edu.ddmath.requestHandler.requestImpl.MyLearnServiceImpl;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.util.DensityUtils;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;
import com.tsinghuabigdata.edu.ddmath.view.CoursePager;
import com.tsinghuabigdata.edu.ddmath.view.LoadingPager;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 我的学习
 * Created by Administrator on 2016/12/14.
 */

public class MyCourseFragment extends MyBaseFragment implements View.OnClickListener, PullToRefreshBase.OnRefreshListener,OnlineTutoringAdapter.TutorListener {

    private static final String TAG = "sky";

    private Context         mContext;
    private ImageView       mIvDoudouteng;
    private TextView        mTvDoudouWork;
    private TextView        mTvOtherWork;
    private TextView        mTvOnlineTutoring;
    private View            mSlider;
    private LinearLayout    mLlClass;
    private TextView        mTvCourseName;
    private CircleImageView mIvTeacherHead1;
    private TextView        mTvTeacherName1;
    private CircleImageView mIvTeacherHead2;
    private TextView        mTvTeacherName2;
    private LinearLayout    mLlClassmate;
    private CircleImageView mIvClassmate1;
    private TextView        mTvClassmate1;
    private CircleImageView mIvClassmate2;
    private TextView        mTvClassmate2;
    private CircleImageView mIvClassmate3;
    private TextView        mTvClassmate3;
    private ImageView       mIvDoudouCamera;
    private ImageView       mIvDoudouHi;
    private ImageView       mIvHi;
    private LinearLayout    mLlCourseContent;
    private ViewPager       mViewPager;
    private LinearLayout    mLlUnregisterTips;
    private LinearLayout    mLlUnregisterPic;
    private Button          mBtnRegister;
    private Button          mBtnLogin;
    private LinearLayout    mLlNoClassTips;

    private View mViewDoudouWork, mViewoOtherWork, mViewOnlineTutoring;

    private PullToRefreshListView mLvDoudouWork;
    private LoadingPager          mLoadingPagerDoudouWork;
    private View                  mViewTosubmit;
    private CheckBox              mCbMore;
    private GridView              mGvToSubmit;

    private PullToRefreshListView mLvTakePhoto;
    private CoursePager           mCoursePager;
    private View                  mViewToUpload;
    private LinearLayout          mLlToUpload;
    private TextView              mTvToUpload;

    private RelativeLayout mRlOnlineTutoringContent;
    private Button         mBtnSelectTutor;
    private TextView       mTvPictureCount;
    private GridView       mGvTutorTeacher;
    private LoadingPager   mLoadingPagerOnlineTutoring;

    private MainActivity  mainActivity;
    private UploadAdatper mAdatper;
    private MyLearnService learnService = new MyLearnServiceImpl();
    private int            pageNum      = 1;
    private int            pageSize     = 20;
    private String accessToken;
    private String studentId;
    private String classId;
    private List<Records> mList = new ArrayList<Records>();
    private boolean toUploadShow;
    private int     mToUploadsize;
    private String  mLoginName;

    private ArrayList<View> aList = new ArrayList<View>();
    private HomePageAdapter mAdapter;
    private int             tabWidth;
    private int currTabIndex = 0; //当前页卡编号
    private ToSubmitAdatper   mToSubmitAdatper;
    private DoudouWorkAdatper mDoudouWorkAdatper;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_my_course, container, false);
        initView(root);
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        mainActivity = (MainActivity) getActivity();
        mIvDoudouteng = (ImageView) root.findViewById(R.id.iv_doudouteng);
        mTvDoudouWork = (TextView) root.findViewById(R.id.tv_doudou_work);
        mTvOtherWork = (TextView) root.findViewById(R.id.tv_other_work);
        mTvOnlineTutoring = (TextView) root.findViewById(R.id.tv_online_tutoring);
        mSlider = root.findViewById(R.id.slider);
        mLlClass = (LinearLayout) root.findViewById(R.id.ll_class);
        mTvCourseName = (TextView) root.findViewById(R.id.tv_course_name);
        mIvTeacherHead1 = (CircleImageView) root.findViewById(R.id.iv_teacher_head1);
        mTvTeacherName1 = (TextView) root.findViewById(R.id.tv_teacher_name1);
        mIvTeacherHead2 = (CircleImageView) root.findViewById(R.id.iv_teacher_head2);
        mTvTeacherName2 = (TextView) root.findViewById(R.id.tv_teacher_name2);
        mLlClassmate = (LinearLayout) root.findViewById(R.id.ll_classmate);
        mIvClassmate1 = (CircleImageView) root.findViewById(R.id.iv_classmate1);
        mTvClassmate1 = (TextView) root.findViewById(R.id.tv_classmate1);
        mIvClassmate2 = (CircleImageView) root.findViewById(R.id.iv_classmate2);
        mTvClassmate2 = (TextView) root.findViewById(R.id.tv_classmate2);
        mIvClassmate3 = (CircleImageView) root.findViewById(R.id.iv_classmate3);
        mTvClassmate3 = (TextView) root.findViewById(R.id.tv_classmate3);
        mIvDoudouCamera = (ImageView) root.findViewById(R.id.iv_doudou_camera);
        mIvDoudouHi = (ImageView) root.findViewById(R.id.iv_doudou_hi);
        mIvHi = (ImageView) root.findViewById(R.id.iv_hi);
        mLlCourseContent = (LinearLayout) root.findViewById(R.id.ll_course_content);
        mViewPager = (ViewPager) root.findViewById(R.id.view_pager);
        mLlUnregisterTips = (LinearLayout) root.findViewById(R.id.ll_unregister_tips);
        mLlUnregisterPic = (LinearLayout) root.findViewById(R.id.ll_unregister_pic);
        mBtnRegister = (Button) root.findViewById(R.id.btn_register);
        mBtnLogin = (Button) root.findViewById(R.id.btn_login);
        mLlNoClassTips = (LinearLayout) root.findViewById(R.id.ll_no_class_tips);
        ViewGroup.LayoutParams layoutParams = mIvDoudouteng.getLayoutParams();
        int fragmentWidth = WindowUtils.getScreenWidth(getActivity()) - DensityUtils.dp2px(getActivity(), 131);
        layoutParams.height = fragmentWidth * 90 / 1782;
        mIvDoudouteng.setLayoutParams(layoutParams);

        tabWidth = DensityUtils.dp2px(getActivity(), 132);
        mViewDoudouWork = getActivity().getLayoutInflater().inflate(R.layout.view_doudou_work, null);
        mViewoOtherWork = getActivity().getLayoutInflater().inflate(R.layout.view_other_work, null);
        mViewOnlineTutoring = getActivity().getLayoutInflater().inflate(R.layout.view_online_tutoring, null);
        aList.add(mViewDoudouWork);
        aList.add(mViewoOtherWork);
        aList.add(mViewOnlineTutoring);
        mAdapter = new HomePageAdapter(aList);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());

        //豆豆作业
        mLvDoudouWork = (PullToRefreshListView) mViewDoudouWork.findViewById(R.id.lv_doudou_work);
        mLoadingPagerDoudouWork = (LoadingPager) mViewDoudouWork.findViewById(R.id.loadingPager_doudou_work);
        //        mLoadingPagerDoudouWork.setTargetView(mLvDoudouWork);
        initDoudouWork();

        //其他作业
        mLvTakePhoto = (PullToRefreshListView) mViewoOtherWork.findViewById(R.id.lv_take_photo);
        mCoursePager = (CoursePager) mViewoOtherWork.findViewById(R.id.coursePager);
        ILoadingLayout loadingLayout = mLvTakePhoto.getLoadingLayoutProxy(true, false);
        loadingLayout.setRefreshingLabel("刷新中...");
        loadingLayout.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh_loading_anim));

        mCoursePager.setTargetView(mLvTakePhoto);
        mLvTakePhoto.setVisibility(View.VISIBLE);
        mList.clear();
        mAdatper = new UploadAdatper(getActivity(), mList);
        mLvTakePhoto.setAdapter(mAdatper);
        mCoursePager.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCoursePager.showLoading();
                queryPhoto();
            }
        });

        //在线辅导
        mRlOnlineTutoringContent = (RelativeLayout) mViewOnlineTutoring.findViewById(R.id.rl_online_tutoring_content);
        mBtnSelectTutor = (Button) mViewOnlineTutoring.findViewById(R.id.btn_select_tutor);
        mTvPictureCount = (TextView) mViewOnlineTutoring.findViewById(R.id.tv_picture_count);
        mGvTutorTeacher = (GridView) mViewOnlineTutoring.findViewById(R.id.gv_tutor_teacher);
        mLoadingPagerOnlineTutoring = (LoadingPager) mViewOnlineTutoring.findViewById(R.id.loadingPager_online_tutoring);
//        mLoadingPagerOnlineTutoring.setTargetView(mRlOnlineTutoringContent);
        initOnlineTutoring();


        mLvTakePhoto.setOnRefreshListener(this);
        mTvDoudouWork.setOnClickListener(this);
        mTvOtherWork.setOnClickListener(this);
        mTvOnlineTutoring.setOnClickListener(this);
        //                mIvCamera.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        mBtnSelectTutor.setOnClickListener(this);
    }


    //豆豆作业本地模拟数据
    private void initDoudouWork() {
        mViewTosubmit = getActivity().getLayoutInflater().inflate(R.layout.view_to_submit, null);
        mCbMore = (CheckBox) mViewTosubmit.findViewById(R.id.cb_to_submit_more);
        mGvToSubmit = (GridView) mViewTosubmit.findViewById(R.id.gv_to_submit);
        mLvDoudouWork.getRefreshableView().addHeaderView(mViewTosubmit);
        List<SubmitQuestion> submitQuestions = new ArrayList<SubmitQuestion>();
        for (int i = 0; i < 4; i++) {
            SubmitQuestion submitQuestion = new SubmitQuestion();
            submitQuestions.add(submitQuestion);
        }
        mToSubmitAdatper = new ToSubmitAdatper(mContext, submitQuestions);
        mGvToSubmit.setAdapter(mToSubmitAdatper);
        mCbMore.setOnClickListener(this);

        List<SumbitedItem> sumbitedItemList = new ArrayList<SumbitedItem>();
        Random random = new Random();
        for (int i = 0; i < 2; i++) {
            SumbitedItem sumbitedItem = new SumbitedItem();
            sumbitedItem.setMonth("2017年" + (7 - i) + "月");
            List<SubmitQuestion> list = new ArrayList<SubmitQuestion>();
            for (int j = 0; j < random.nextInt(10); j++) {
                SubmitQuestion question = new SubmitQuestion();
                list.add(question);
            }
            sumbitedItem.setQuestions(list);
            sumbitedItemList.add(sumbitedItem);
        }
        mDoudouWorkAdatper = new DoudouWorkAdatper(mContext, sumbitedItemList);
        mLvDoudouWork.setAdapter(mDoudouWorkAdatper);
    }

    //在线辅导本地模拟数据
    private void initOnlineTutoring() {
        List<OnlineTutoring> onlineTutorings = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            OnlineTutoring vo = new OnlineTutoring();
            vo.setName(i+"号");
            onlineTutorings.add(vo);
        }
        OnlineTutoringAdapter onlineTutoringAdapter = new OnlineTutoringAdapter(mContext, onlineTutorings,this);
        mGvTutorTeacher.setAdapter(onlineTutoringAdapter);
    }


    private void initData() {
        //        mIvHead.setImageResource(R.drawable.personalcenter_bg_defaultface_onlydoudou);
        mViewToUpload = getActivity().getLayoutInflater().inflate(R.layout.view_to_upload, null);
        mLlToUpload = (LinearLayout) mViewToUpload.findViewById(R.id.ll_to_upload);
        mTvToUpload = (TextView) mViewToUpload.findViewById(R.id.tv_to_upload);
        ViewGroup.LayoutParams layoutParams = mLlToUpload.getLayoutParams();
        int width = WindowUtils.getScreenWidth(getActivity()) - DensityUtils.dp2px(getActivity(), 435);
        layoutParams.width = width / 5;
        layoutParams.height = width * 109 / 120 / 5;
        mLlToUpload.setLayoutParams(layoutParams);
        mLlToUpload.setOnClickListener(this);
        //        queryInfo();
        IntentFilter intentFilter = new IntentFilter(AppConst.ACTION_UPLOAD_SUCCESS);
        mainActivity.registerReceiver(new UploadSuccessReceiver(), intentFilter);
    }


    public void queryInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            accessToken = loginInfo.getAccessToken();
            mLoginName = loginInfo.getLoginName();
            Log.i(TAG, "accessToken=" + accessToken + "mLoginName=" + mLoginName);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {
                showNoClassView();
            } else {
                classId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                studentId = detailinfo.getStudentId();
                Log.i(TAG, "classId=" + classId + "studentId=" + studentId);
                queryClass();
                queryPhoto();
                showCourseContentView();
            }
            queryUploadSize();
        } else {
            showUnregisterView();
        }
    }

    private void showUnregisterView() {
        //        mTvTakePhoto.setActivated(false);
        mLlUnregisterTips.setVisibility(View.VISIBLE);
        mLlNoClassTips.setVisibility(View.INVISIBLE);
        mLlCourseContent.setVisibility(View.INVISIBLE);
        mLlClass.setVisibility(View.INVISIBLE);
    }

    private void showNoClassView() {
        //        mTvTakePhoto.setActivated(false);
        mLlUnregisterTips.setVisibility(View.INVISIBLE);
        mLlNoClassTips.setVisibility(View.VISIBLE);
        mLlCourseContent.setVisibility(View.INVISIBLE);
        mLlClass.setVisibility(View.INVISIBLE);
    }

    private void showCourseContentView() {
        //        mTvTakePhoto.setActivated(true);
        mLlUnregisterTips.setVisibility(View.INVISIBLE);
        mLlNoClassTips.setVisibility(View.INVISIBLE);
        mLlCourseContent.setVisibility(View.VISIBLE);
    }


    @Override
    public void onResume() {
        Log.i(TAG, "MyCourseFragment onResume()");
        super.onResume();
        if (!TextUtils.isEmpty(mLoginName)) {
            queryUploadSize();
        }
    }

    private void queryUploadSize() {
        LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager(getActivity(), mLoginName);
        mToUploadsize = localWorkManager.getWaitWorkList().size();
        Log.i(TAG, "mLoginName=" + mLoginName + "size=" + mToUploadsize);
        if (mToUploadsize > 0) {
            showUploadView(true);
            mTvToUpload.setText("已有" + mToUploadsize + "组图片，请尽快上传");
        } else {
            showUploadView(false);
        }
    }


    private void showUploadView(boolean show) {
        if (show == toUploadShow) {
            return;
        }
        if (show) {
            mLvTakePhoto.getRefreshableView().addHeaderView(mViewToUpload);
        } else {
            mLvTakePhoto.getRefreshableView().removeHeaderView(mViewToUpload);
        }
        toUploadShow = show;
    }

    public void queryClass() {
        QueryClassTask queryClassTask = new QueryClassTask(new RequestListener<ClassInfo>() {
            @Override
            public void onSuccess(ClassInfo vo) {
                Log.i(TAG, "queryClass onSuccess");
                if (vo == null) {
                    mainActivity.setQueryClassSuccess(false);
                    ToastUtils.showShort(getActivity(), R.string.server_error);
                    return;
                }
                mainActivity.setQueryClassSuccess(true);
                mTvCourseName.setText(vo.getClassName());
                TeacherBean teacherBean = vo.getTeacher();
                if (teacherBean != null) {
                    mTvTeacherName1.setText(teacherBean.getReallyName() + "老师");
                    SetHeadImage.setHeadIncomplete(getContext(), mIvTeacherHead1, teacherBean.getHeadImage(), R.drawable.ico_teacher_head_normal);
                }
                //// TODO: 2017/3/9 增加到2老师
                List<StudentsBean> studentsList = vo.getStudents();
                if (studentsList != null && studentsList.size() > 0) {
                    List<StudentsBean> otherList = DataUtils.getOtherStudents(studentsList, studentId);
                    int size = otherList.size();
                    if (size > 0) {
                        mLlClassmate.setVisibility(View.VISIBLE);
                        StudentsBean studentsBean1 = otherList.get(0);
                        if (studentsBean1 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean1.getReallyName());
                            mTvClassmate1.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate1, studentsBean1.getHeadImage());
                        }
                    }
                    if (size > 1) {
                        StudentsBean studentsBean2 = otherList.get(1);
                        if (studentsBean2 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean2.getReallyName());
                            mTvClassmate2.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate2, studentsBean2.getHeadImage());
                        }
                    }
                    if (size > 2) {
                        StudentsBean studentsBean3 = otherList.get(2);
                        if (studentsBean3 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean3.getReallyName());
                            mTvClassmate3.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate3, studentsBean3.getHeadImage());
                        }
                    }
                }
                mLlClass.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFail(HttpResponse<ClassInfo> response, Exception ex) {
                Log.i(TAG, "queryClass onFail");
                mainActivity.setQueryClassSuccess(false);
                ToastUtils.showShort(getActivity(), R.string.server_error);
            }
        });
        if (!TextUtils.isEmpty(classId)) {
            queryClassTask.execute(accessToken, classId);
        }
    }


    private void queryPhoto() {
        QueryMyCourseTask task = new QueryMyCourseTask(new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "queryPhoto onSuccess");
                if (resList == null || resList.size() == 0) {
                    mCoursePager.showEmpty();
                    return;
                }
                Log.i(TAG, "resList.size()=" + resList.size());
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                if (mAdatper == null) {
                    mAdatper = new UploadAdatper(getActivity(), mList);
                    mLvTakePhoto.setAdapter(mAdatper);
                } else {
                    mAdatper.notifyDataSetChanged();
                }
                if (resList.size() < pageSize) {
                    Log.i(TAG, "PULL_FROM_START");
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    Log.i(TAG, "BOTH");
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mCoursePager.showTarget();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                Log.i(TAG, "queryPhoto onFail");
                mCoursePager.showFault();
            }
        });
        task.execute(accessToken, studentId, classId, pageNum + "", pageSize + "");
    }

    private void select(int i) {
        AppLog.i(TAG, "select i= " + i);
        if (currTabIndex == i) {
            return;
        }
        Animation animation = new TranslateAnimation(currTabIndex * tabWidth, i * tabWidth, 0, 0);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        mSlider.startAnimation(animation);
        mViewPager.setCurrentItem(i);
        if (i == 0) {
            mIvDoudouCamera.setVisibility(View.VISIBLE);
            mIvDoudouHi.setVisibility(View.INVISIBLE);
            mIvHi.setVisibility(View.INVISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT_BOLD);
            mTvOtherWork.setTypeface(Typeface.DEFAULT);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT);
        } else if (i == 1) {
            mIvDoudouCamera.setVisibility(View.INVISIBLE);
            mIvDoudouHi.setVisibility(View.VISIBLE);
            mIvHi.setVisibility(View.VISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT);
            mTvOtherWork.setTypeface(Typeface.DEFAULT_BOLD);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT);
        } else if (i == 2) {
            mIvDoudouCamera.setVisibility(View.INVISIBLE);
            mIvDoudouHi.setVisibility(View.VISIBLE);
            mIvHi.setVisibility(View.VISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT);
            mTvOtherWork.setTypeface(Typeface.DEFAULT);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT_BOLD);
        }
        currTabIndex = i;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                mainActivity.switchFragment(MainActivity.FRAGMENT_MY_CENTER);
                goFragment(new RegisterFragment());
                break;
            case R.id.btn_login:
                mainActivity.switchFragment(MainActivity.FRAGMENT_MY_CENTER);
                goFragment(new LoginFragment());
                break;
            case R.id.tv_doudou_work:
                select(0);
                break;
            case R.id.tv_other_work:
                select(1);
                break;
            case R.id.tv_online_tutoring:
                select(2);
                break;
            case R.id.cb_to_submit_more:

                break;
            case R.id.iv_camera: {
                mToUploadsize = 0;
                LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager();
                if (localWorkManager != null) {
                    WaitWorkBean workBean = localWorkManager.getNotUploadWaitWork();
                    if (workBean != null) {
                        mToUploadsize = workBean.getImageList().size();
                    }
                }
                if (mToUploadsize > 12) {
                    ToastUtils.showToastCenter(getActivity(), "不能继续拍摄，\n未上传图片最多12张哦~");
                } else {
                    Intent intent = new Intent(getActivity(), XBookCameraActivity.class);
                    startActivity(intent);
                }
            }
            break;
            case R.id.ll_to_upload: {
                Intent intent = new Intent(getActivity(), WaitUploadActivity.class);
                startActivity(intent);
            }
            case R.id.btn_select_tutor:
//                SelectTimeDialog selectTimeDialog = new SelectTimeDialog(mContext);
//                selectTimeDialog.show();
            {
                Intent intent = new Intent(getActivity(), SelectQuestionsActivity.class);
                startActivity(intent);
            }
                break;
        }
    }

    @Override
    public void onRefresh(PullToRefreshBase pullToRefreshBase) {
        if (pullToRefreshBase.isHeaderShown()) {
            refreshData();
        } else {
            getMoreData();
        }
    }

    private void getMoreData() {
        pageSize += 20;
        QueryMyCourseTask task = new QueryMyCourseTask(new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "resList.size()=" + resList.size());
                if (resList == null || resList.size() == 0) {
                    ToastUtils.showShort(getActivity(), R.string.server_error);
                    mLvTakePhoto.onRefreshComplete();
                    return;
                }
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                mAdatper.notifyDataSetChanged();
                if (resList.size() < pageSize) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mLvTakePhoto.onRefreshComplete();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                ToastUtils.showShort(getActivity(), R.string.server_error);
                mLvTakePhoto.onRefreshComplete();
            }
        });
        task.execute(accessToken, studentId, classId, pageNum + "", pageSize + "");
    }

    private void refreshData() {
        pageSize = 20;
        QueryMyCourseTask task = new QueryMyCourseTask(new RequestListener<List<MyCourse>>() {
            @Override
            public void onSuccess(List<MyCourse> resList) {
                Log.i(TAG, "resList.size()=" + resList.size());
                if (resList == null || resList.size() == 0) {
                    ToastUtils.showShort(getActivity(), R.string.server_error);
                    mLvTakePhoto.onRefreshComplete();
                    return;
                }
                List<Records> recordsList = DataUtils.select(resList);
                mList.clear();
                mList.addAll(recordsList);
                mAdatper.notifyDataSetChanged();
                if (resList.size() < pageSize) {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    mLvTakePhoto.setMode(PullToRefreshBase.Mode.BOTH);
                }
                mLvTakePhoto.onRefreshComplete();
            }

            @Override
            public void onFail(HttpResponse<List<MyCourse>> response, Exception ex) {
                ToastUtils.showShort(getActivity(), R.string.server_error);
                mLvTakePhoto.onRefreshComplete();
            }
        });
        task.execute(accessToken, studentId, classId, pageNum + "", pageSize + "");
    }

    @Override
    public void selectTimeClick(String teacherId, int position) {

    }

    @Override
    public void sendTutorClick(String teacherId, int position) {
        SelectTimeDialog selectTimeDialog = new SelectTimeDialog(mContext);
        selectTimeDialog.show();
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            AppLog.i(TAG, "onPageSelected position= " + position);
            select(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 查询我的课程
     */
    class QueryMyCourseTask extends AppAsyncTask<String, Void, List<MyCourse>> {

        private RequestListener reqListener;

        public QueryMyCourseTask(RequestListener requestListener) {
            reqListener = requestListener;
        }

        @Override
        protected List<MyCourse> doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String studentId = params[1];
            String classId = params[2];
            int pageNum = Integer.parseInt(params[3]);
            int pageSize = Integer.parseInt(params[4]);
            return learnService.myCourse(accessToken, studentId, classId, pageNum, pageSize);
        }

        @Override
        protected void onResult(List<MyCourse> myCourses) {
            reqListener.onSuccess(myCourses);
        }

        @Override
        protected void onFailure(HttpResponse<List<MyCourse>> response, Exception ex) {
            reqListener.onFail(response, ex);
        }


    }

    /**
     * 查询班级的老师和所有学生信息
     */
    class QueryClassTask extends AppAsyncTask<String, Void, ClassInfo> {

        private RequestListener reqListener;

        public QueryClassTask(RequestListener requestListener) {
            reqListener = requestListener;
        }

        @Override
        protected ClassInfo doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String classId = params[1];
            return learnService.queryClassInfo(accessToken, classId);
        }

        @Override
        protected void onResult(ClassInfo classInfo) {
            reqListener.onSuccess(classInfo);
        }

        @Override
        protected void onFailure(HttpResponse<ClassInfo> response, Exception ex) {
            reqListener.onFail(response, ex);
        }


    }

    /**
     * 图片上传成功广播接收者
     */
    class UploadSuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听消息
            if (AppConst.ACTION_UPLOAD_SUCCESS.equals(intent.getAction())) {
                Log.i(TAG, "MyCourseFragment UploadSuccessReceiver");
                if (!TextUtils.isEmpty(classId) && !TextUtils.isEmpty(studentId)) {
                    queryPhoto();
                }
            }
        }
    }


}
